package com.javacodegeeks.enterprise.rest.jersey;

import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;

import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import json.*;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

@Path("/googgledrive")
public class GoogleDriverAPI implements IClouding{

	private String acToken;
	private String tokenType;
	private String uid;
	DefaultHttpClient httpClient;

	// private List<FileGoogleDriver> files = new ArrayList<FileGoogleDriver>();
	@POST
	@Path("/login")
	public Response login(@FormParam("access_token") String access_token,
			@FormParam("token_type") String token_type,
			@FormParam("uid") String uid) throws IOException,
			URISyntaxException {
		this.acToken = access_token;
		this.tokenType = token_type;

		// System.out.println(access_token);
		URL url = new URL(
				"https://www.googleapis.com/oauth2/v1/userinfo?access_token="
						+ access_token);

		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		int serverCode = con.getResponseCode();
		 System.out.println(serverCode);

		InputStream in = con.getInputStream();
		OutputStream os = new DataOutputStream(new FileOutputStream("user.json"));
		final int length = 5000;
		byte[] bytes = new byte[length];
		int bytesRead = 0;
		while ((bytesRead = in.read(bytes, 0, length)) > 0) {
			os.write(bytes, 0, bytesRead);
			os.flush();
		}
		os.close();

		// Get root folder metadata.
		httpClient = new DefaultHttpClient();

		// https://www.googleapis.com/drive/v2/files?q='root'+in+parents&fields=items(id%2CmimeType%2Cthumbnail%2Ctitle)&key={YOUR_API_KEY}
		// HttpGet("https://www.googleapis.com/drive/v2/files?q='root'+in+parents&key=45339683173.apps.googleusercontent.com");

		HttpGet getRequest = new HttpGet(
				"https://www.googleapis.com/drive/v2/files?q='root'+in+parents&fields=items(id%2CmimeType%2Cthumbnail%2Ctitle)&key=45339683173.apps.googleusercontent.com");
		getRequest.addHeader("Content-Type", "application/json");

		// getRequest.addHeader("Authorization",
		// "Bearer ya29.1.AADtN_Vl7UVQGcfR9fjFkr2lYBv6P2Ox2o6TG1yVH987aycoB2V8IqYjsUEJtlP94JO1WA");
		getRequest.addHeader("Authorization", "Bearer " + access_token);

		System.out.println(getRequest.getURI());
		HttpResponse response = httpClient.execute(getRequest);

		HttpEntity entity = response.getEntity();
		String responseString = EntityUtils.toString(entity);

		System.out.println(responseString);

		// save json
		saveData("test1.json", responseString);

		// -------load sub file
		JsonParse.createlistFileFromJson("test1.json");

		return Response.seeOther(new URI("../rest/googgledrive/explorer")).build();
	}

	@GET
	@Path("/explorer")
	@Produces(MediaType.TEXT_HTML)
	public String getfile() {
		// JsonParse.createlistFileFromJson("test1.json");
		System.out.println("file load " + JsonParse.files.size());
		User u = JsonParse.createuserJson("user.json");
		String html = "";

		html += "<script type=\"text/javascript\" src=\"..\\simpletreemenu.js\"> </script>";
		html += "<link rel=\"stylesheet\" type=\"text/css\" href=\"..\\simpletree.css\" />";
		html += " Hello " + u.getName() + " " + u.getGmail() + ", you have : "
				+ JsonParse.files.size() + "files <br>";

		html += "<ul id=\"treemenu1\" class=\"treeview\">";

		for (int i = 0; i < JsonParse.files.size(); i++) {

			html += "<li><a href src=''><img src=\"image\\closed.gif\">"
					+ JsonParse.files.get(i).getTitle() + "</a></li>";
		}

		html += "</ul> <script type=\"text/javascript\"> ddtreemenu.createTree(\"treemenu1\", true) </script>";
		return html;
	}

	// save data tofile
	public void saveData(String filename, String responseString) {
		OutputStream os1;
		try {
			os1 = new DataOutputStream(new FileOutputStream(filename));
			os1.write(responseString.getBytes());
			os1.flush();
			os1.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	

	// load subfile
	public void loadfilefromsubfile(String id_folder)
			throws ClientProtocolException, IOException {
		HttpGet getRequest = new HttpGet(
				"https://www.googleapis.com/drive/v2/files?q='"
						+ id_folder
						+ "'+in+parents&fields=items(id%2CmimeType%2Cthumbnail%2Ctitle)&key=45339683173.apps.googleusercontent.com");
		getRequest.addHeader("Content-Type", "application/json");

		// getRequest.addHeader("Authorization",
		// "Bearer ya29.1.AADtN_Vl7UVQGcfR9fjFkr2lYBv6P2Ox2o6TG1yVH987aycoB2V8IqYjsUEJtlP94JO1WA");
		getRequest.addHeader("Authorization", "Bearer " + acToken);

		System.out.println(getRequest.getURI());
		HttpResponse response = httpClient.execute(getRequest);

		HttpEntity entity = response.getEntity();
		String responseString = EntityUtils.toString(entity);

		System.out.println(responseString);

		// save json
	}

	public void loadfilefromGD(List<FileGoogleDriver> files)
			throws ClientProtocolException, IOException {

		for (int i = 0; i < files.size(); i++) {
			FileGoogleDriver f = files.get(i);
			if (f.getMimeType().equals("application/vnd.google-apps.folder")) {
				HttpGet getRequest = new HttpGet(
						"https://www.googleapis.com/drive/v2/files?q='"
								+ f.getId()
								+ "'+in+parents&key=45339683173.apps.googleusercontent.com");
				getRequest.addHeader("Content-Type", "application/json");
				getRequest.addHeader("Authorization", "Bearer " + this.acToken);
				System.out.println(getRequest.getURI());
				HttpResponse response1 = httpClient.execute(getRequest);
				HttpEntity entity1 = response1.getEntity();
				String responseString1 = EntityUtils.toString(entity1);
				System.out.println(responseString1);
				// save json
				OutputStream os2 = new DataOutputStream(new FileOutputStream(
						"subfile.json", true));
				os2.write(responseString1.getBytes());
				os2.flush();
				os2.close();
			}
		}

	}

	public void UploadFile(String destPath, String filePath) {
		// TODO Auto-generated method stub
		
	}

	public void moveAndRenameFile(String fromPath, String toPath) {
		// TODO Auto-generated method stub
		
	}

	public void getFile(String path) {
		// TODO Auto-generated method stub
		
	}

	public void getListFile(String pathname) {
		// TODO Auto-generated method stub
		
	}

	public void getsizeFile(String path) {
		// TODO Auto-generated method stub
		
	}

}
